`include "define.v"

module regfile (
    input wire rst,
    input wire clk,
    //写端口
    input wire[`RegAddrBus] reg_write_addr,
    input wire[`RegBus] reg_write_data,
    input wire write_enable,

    //读端口1
    input wire[`RegAddrBus] raddr1,
    input wire raddr1_enable,
    output reg[`RegBus] reg_read_data1,
    //读端口2
    input wire[`RegAddrBus] raddr2,
    input wire raddr2_enable,
    output reg[`RegBus] reg_read_data2
);

    reg[`RegBus] regs[0: `RegNum-1];

    //写操作
    always @(posedge clk) begin
        if (rst == `RstDisable) begin
            if (write_enable == `WriteEnable) begin
                regs[reg_write_addr] <= reg_write_data;
            end
        end
    end

    //读操作 reg1
    always @(*) begin
        if (rst == `RstEnable) begin
            reg_read_data1 <= `ZeroWord;
        end else if(raddr1 == `RegNumLog2'h0) begin
            reg_read_data1 <= `ZeroWord;
        end else if((raddr1 == reg_write_addr) && (raddr1_enable == `ReadEnable)
                        && (write_enable == `WriteEnable)) begin
            reg_read_data1 <= reg_write_data;
        end else if(raddr1_enable == `ReadEnable) begin
            reg_read_data1 <= regs[raddr1];
        end else begin
            reg_read_data1 <= `ZeroWord;
        end
    end

    //读操作 reg2
    always @(*) begin
        if (rst == `RstEnable) begin
            reg_read_data2 <= `ZeroWord;
        end else if(raddr2 == `RegNumLog2'h0) begin
            reg_read_data2 <= `ZeroWord;
        end else if((raddr2 == reg_write_addr) && (raddr2_enable == `ReadEnable)
                        && (write_enable == `WriteEnable)) begin
            reg_read_data2 <= reg_write_data;
        end else if(raddr2_enable == `ReadEnable) begin
            reg_read_data2 <= regs[raddr2];
        end else begin
            reg_read_data2 <= `ZeroWord;
        end
    end
endmodule
